<template>
  <div class="upload-section">
    <el-upload
      class="upload-area"
      drag
      :action="uploadUrl"
      multiple
      :show-file-list="false"
      :on-progress="handleProgress"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :on-error="handleError"
      :headers="headers"
      method="post"
      :data="dataParams"
    >
      <div class="upload-content">
        <i class="el-icon-upload">
          <img src="~@/static/upload-download.png" class="upload-icon" alt="">
        </i>
        <div class="upload-text">点击或将作业文件拖拽到上传</div>
      </div>
    </el-upload>
    
    <div class="file-list">
      <div v-for="(file, index) in uploadFiles" :key="file.name" class="file-item">
        <div class="file-info">
          <span class="filename">{{ file.name }}</span>
          <i class="el-icon-close" >
            <el-icon @click="handleRemoveFile(file, index)"><Close /></el-icon>
          </i>
        </div>
        <div v-if="file.status === 'uploading'&&file.percentage!=100" class="progress-bar">
          <div class="progress" :style="{ width: file.percentage + '%' }"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { useUserStore } from '@/stores/User';
import { myHomeworkFileDelete } from '@/service/personalCenter';
import { ElMessage } from 'element-plus';
const userStore = useUserStore();
const token = userStore.userInfo?.token;
const headers = ref({});
const dataParams = ref({});

const uploadFiles = ref([])

const props = defineProps({
  fileList: {
    type: Array,
    default: () => []
  },
  uploadUrl: {
    type: String,
    required: true
  },
  eid: {
    type: [String, Number],
    required: true
  },
  isRemove: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['updateFileList'])

// 初始化：转换父组件文件格式
onMounted(() => {
  if (props.fileList && props.fileList.length > 0) {
    uploadFiles.value = props.fileList.map(file => ({
      ...file,
      uid: generateUniqueId(), // 生成唯一ID
      status: 'success',
      percentage: 100
    }))
    console.log('初始化文件列表:', uploadFiles.value)
  }
})


// 监听父组件fileList变化（深拷贝处理）
watch(() => props.fileList, (newVal) => {
  // 直接使用父组件传来的文件列表，保留重要的字段
  const serverFiles = newVal.map(file => ({
    ...file,
    uid: generateUniqueId(),
    status: 'success',
    percentage: 100
  }))
  
  // 合并服务端文件 + 本地正在上传的文件
  uploadFiles.value = [
    ...serverFiles,
    ...uploadFiles.value.filter(f => f.status === 'uploading')
  ]
}, { deep: true })

// 生成唯一ID
const generateUniqueId = () => Date.now().toString(36) + Math.random().toString(36).substr(2)

const beforeUpload = (file) => {
  // 避免重复添加
  if (uploadFiles.value.some(f => f.uid === file.uid)) return false
  headers.value.token = token;
  
  if(props.eid) {
    dataParams.value = { eid: props.eid, name: file.name }
  }
  
  uploadFiles.value.push({
    ...file,
    uid: file.uid, // 使用element生成的uid
    status: 'uploading',
    percentage: 0,
    id: null // 等待上传成功后赋值
  })
  return true
}


const handleProgress = (event, file) => {
  const targetFile = uploadFiles.value.find(f => f.uid === file.uid)
  if (targetFile) {
    // 计算真实进度
    const percent = Math.round((event.loaded / event.total) * 100)
    targetFile.percentage = percent
  }
}

const handleSuccess = (response, uploadFile) => {
  const targetFile = uploadFiles.value.find(f => f.uid === uploadFile.uid)
  if (targetFile && response.code === '000000') {
    // 统一数据结构
    Object.assign(targetFile, {
      id: response.data.id,
      name: uploadFile.name, // 确保保留原始文件名
      url: response.data.url, // 确保包含父组件需要的字段
      size: uploadFiles.size,
      status: 'success',
      percentage: 100
    })
    
    // 触发更新
    emit('updateFileList', uploadFiles.value
      .filter(f => f.status === 'success')
      .map(({ uid, status, percentage, ...rest }) => rest) // 只保留父组件需要的字段
    )
  } else {
    ElMessage.error(`${targetFile.name} 上传失败`)
  }
}

const handleError = (error, file) => {
  const targetFile = uploadFiles.value.find(f => f.uid === file.uid)
  if (targetFile) {
    targetFile.status = 'error'
    ElMessage.error(`${file.name} 上传失败`)
  }
}

const handleRemoveFile = async(file, index) => {
  // 如果 isRemove 为 true 且文件有 id，查找对应的文件
  const fileIndex = props.isRemove && file.id ? 
    uploadFiles.value.findIndex(f => f.id === file.id) : index;
  
  if (fileIndex !== -1) {
    try {
      // 根据isRemove属性决定是否调用删除接口
      if (props.isRemove && file.id) {
        // 如果isRemove为true且有id，走接口删除
        const res = await myHomeworkFileDelete({ id: file.id })
        
        // 删除本地记录
        uploadFiles.value.splice(fileIndex, 1)
        
        // 更新父组件
        const validFiles = uploadFiles.value
          .filter(f => f.status === 'success')
          .map(({ uid, status, percentage, ...rest }) => rest) // 移除临时字段
        emit('updateFileList', validFiles)

        // 提示处理
        res.code === '000000' 
          ? ElMessage.success('附件删除成功')
          : ElMessage.error('附件删除失败')
      } else {
        // 如果isRemove为false，只进行本地UI删除，不调用接口
        uploadFiles.value.splice(fileIndex, 1)
        
        // 更新父组件
        const validFiles = uploadFiles.value
          .filter(f => f.status === 'success')
          .map(({ uid, status, percentage, ...rest }) => rest) // 移除临时字段
        emit('updateFileList', validFiles)
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }
}
</script>

<style lang="scss" scoped>
.upload-section {
  .upload-text {
    color: #126983;
    font-size: 14px;
  }
  
  .file-list {
    width:100%;
    display:flex;
    flex-wrap:wrap;
    gap:10px;
    margin-top: 20px;
  }

  .file-item {
    background: #fff;
    border: 1px solid #CCCCCC;
    border-radius: 8px;
    margin-bottom: 12px;
    overflow: hidden;
    width: 32%;
    min-width:32%;
    box-shadow: none;
    position: relative;
  }

  .file-info {
    padding: 12px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    cursor: pointer;
  }

  .progress-bar {
    height: 4px;
    background: #E5E5E5;
    position: absolute;
    bottom:0px;
    
    width: 100%;
    .progress {
      height: 100%;
      background: #126983;
      transition: width 0.3s ease;
      border-radius: 0;
    }
  }
}

.upload-icon{
  width: 26px;
height: 30px;


}
:deep(.el-upload-dragger){
  border:1px dashed #126983;
}

.filename {
  color: #333;
  font-size: 14px;
}
</style>